package com.zhongge.gui;

import com.zhongge.book.Book;
import com.zhongge.book.BookList;
import com.zhongge.operations.ReturnBook;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 归还图书对话框
 */
public class ReturnBookDialog extends JDialog {
    private BookList bookList;
    private JTextField nameField;
    private boolean returnCompleted = false;
    
    public ReturnBookDialog(Frame parent, BookList bookList) {
        super(parent, "归还图书", true);
        this.bookList = bookList;
        initUI();
        setSize(400, 200);
        setLocationRelativeTo(parent);
    }
    
    /**
     * 初始化界面
     */
    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 输入面板
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel nameLabel = new JLabel("书名: ");
        nameField = new JTextField(20);
        JButton searchButton = new JButton("查找");
        searchButton.addActionListener(new SearchListener());
        
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);
        inputPanel.add(searchButton);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        JButton returnButton = new JButton("归还");
        JButton cancelButton = new JButton("取消");
        
        returnButton.addActionListener(new ReturnListener());
        cancelButton.addActionListener(e -> dispose());
        
        buttonPanel.add(returnButton);
        buttonPanel.add(cancelButton);
        
        // 添加到主面板
        mainPanel.add(inputPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        setContentPane(mainPanel);
    }
    
    /**
     * 查找按钮监听器
     */
    private class SearchListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String bookName = nameField.getText().trim();
            if (bookName.isEmpty()) {
                JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                        "请输入书名", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 查找图书并检查状态
            boolean found = false;
            boolean isBorrowed = false;
            
            for (int i = 0; i < bookList.getUsedSize(); i++) {
                Book book = bookList.getBook(i);
                if (bookName.equals(book.getName())) {
                    found = true;
                    isBorrowed = book.isBorrow();
                    break;
                }
            }
            
            if (found) {
                String status = isBorrowed ? "已借出" : "未借出";
                JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                        "找到图书《" + bookName + "》\n状态: " + status, 
                        "图书信息", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                        "未找到图书《" + bookName + "》", "提示", JOptionPane.WARNING_MESSAGE);
            }
        }
    }
    
    /**
     * 归还按钮监听器
     */
    private class ReturnListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String bookName = nameField.getText().trim();
            if (bookName.isEmpty()) {
                JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                        "请输入书名", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 检查图书是否存在且已借出
            Book targetBook = null;
            for (int i = 0; i < bookList.getUsedSize(); i++) {
                Book book = bookList.getBook(i);
                if (bookName.equals(book.getName())) {
                    targetBook = book;
                    break;
                }
            }
            
            if (targetBook == null) {
                JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                        "未找到图书《" + bookName + "》", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            if (!targetBook.isBorrow()) {
                JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                        "图书《" + bookName + "》未借出", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            // 调用原有ReturnBook实现归还功能
            ReturnBook returnOperation = new ReturnBook();
            
            // 创建自定义输入流模拟控制台输入
            ConsoleInputSimulator inputSimulator = new ConsoleInputSimulator();
            inputSimulator.provideInput(bookName + "\n");
            inputSimulator.startSimulation();
            
            try {
                // 执行归还操作
                returnOperation.work(bookList);
                
                // 检查是否归还成功
                if (!targetBook.isBorrow()) {
                    returnCompleted = true;
                    JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                            "图书《" + bookName + "》归还成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                            "归还失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(ReturnBookDialog.this, 
                        "归还失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            } finally {
                inputSimulator.stopSimulation();
            }
        }
    }
    
    /**
     * 判断归还是否完成
     */
    public boolean isReturnCompleted() {
        return returnCompleted;
    }
    
    /**
     * 控制台输入模拟工具类
     */
    private class ConsoleInputSimulator {
        private java.io.ByteArrayInputStream inBuffer;
        private java.io.InputStream originalIn;
        
        public void provideInput(String input) {
            inBuffer = new java.io.ByteArrayInputStream(input.getBytes());
        }
        
        public void startSimulation() {
            originalIn = System.in;
            System.setIn(inBuffer);
        }
        
        public void stopSimulation() {
            System.setIn(originalIn);
        }
    }
}